<?php

class DevicesController extends Zend_Controller_Action {

    protected $_log;
    protected $doctrineContainer;

    public function init() {
        $this->_log = Zend_Registry::get('log');
        $this->doctrineContainer = Zend_Registry::get('doctrine');
    }

    public function indexAction() {
        $this->view->headTitle($this->view->translate->_('Devices'), 'PREPEND');
        $em = $this->doctrineContainer->getEntityManager();
        $devices = $em->getRepository('Jhub1db\Entity\Jhub1device')->getAllOrdered();
                #findAll();
        $this->view->devices = $devices;
        #$dbus = new Application_Model_Dbus();
        #$dbus->getDeviceValue("bool");
    }

    public function belongAction() {
        $hubid = $this->_getParam('hubid');
        $this->view->headTitle($this->view->translate->_('Devices for hub'), 'PREPEND');
        $em = $this->doctrineContainer->getEntityManager();
        $devices = $em->getRepository('Jhub1db\Entity\Jhub1device')->findBy(array('jhub1service' => $hubid));
        $service = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hubid));
        $this->view->agent = $service[0]->getAgentdev();
        $this->view->devices = $devices;
        $this->view->hubid = $hubid;
    }

    public function editAction() {
        $devid = $this->_getParam('devid');
        $hubid = $this->_getParam('hubid');        
        $this->view->headTitle($this->view->translate->_("Edit device's attributes"), 'PREPEND');
        $this->view->hubid = $hubid;
        $em = $this->doctrineContainer->getEntityManager();
        if ($devid > 0) {
            $devices = $em->getRepository('Jhub1db\Entity\Jhub1device')->findBy(array('jhub1attributes' => $devid));
            $deviceType = $devices[0]->getDevicetype();
            $attributes = $em->getRepository('Jhub1db\Entity\Jhub1attributes')->findBy(array('id' => $devid));            
            $attributesArr = $attributes[0]->getAttributes();
            $this->view->deviceType = $deviceType;
            $config = new Zend_Config_Ini(APPLICATION_PATH . "/forms/DefaultAttributesConfigForm.ini", 'development');
            $form = new Jhub1_Form($config->user->agent);
           #
            $form->populate($attributesArr);
            $adoptedForm = $this->selectFields($deviceType,$form,"/devices/edit");
                    
            $this->view->form = $adoptedForm;     
        }
  /*                  
            if ($this->_request->isPost()) {
                $formData = $this->_request->getPost();
                if ($adoptedForm->isValid($formData)) {
                    $this->_redirect("devices/addaddress");   
                } else {
                    $adoptedForm->populate($formData);
                }
            }
   * *
   */   
    }
    
#ADD DEVICE PROCESS
    public function addAction() { 
        $this->_helper->layout()->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();
        $addSession = new Zend_Session_Namespace('addDevice');    
        $addSession->hubid = $this->_getParam('hubid');
        $this->_log->info("DEVICE ADD action triggered for service: " . $addSession->hubid);
        
        $this->_redirect("devices/addaddress"); 
    }
    
    public function addaddressAction() {        
        $addSession = new Zend_Session_Namespace('addDevice');
        $this->view->headTitle($this->view->translate->_('Add new device'), 'PREPEND');
      #  echo $this->_getParam('hubid');
      #  die;
      #  $devid = 
      #  if(defined($this->_getParam('devid')) && $this->_getParam('devid') > 0) {
        
      #  echo $addSession->hubid;
      #  } else {
       #     if(defined($addSession->devid) && $addSession->devid > 0) {
        #        
         #   } else {
          #      $this->_redirect("devices/index");
           # }
        #}
       # $addSession->devid = $devid;
        
        if ($this->_getParam('address') != "") {
            if($this->_getParam('address') != $addSession->address) {
             #  zero proggress $addSession->address = 0;
             #   $addSession->basicConfig = 0;
             #   $addSession->serviceConfig = "";
             #   $addSession->serviceMainConfig = "";
             #   $addSession->serviceConfig = "";
             #   $addSession->serviceRawConfig = "";               
            }
            $addSession->address = $this->_getParam('address');
            $this->_redirect("devices/addtype");            
        }
        $this->view->address = $addSession->address;
    }

    public function addtypeAction() {
        $addSession = new Zend_Session_Namespace('addDevice');
        echo $addSession->hubid;
        $this->view->headTitle($this->view->translate->_('Add new device'), 'PREPEND');  
        if ($this->_getParam('devType') != "") {
            if($this->_getParam('devType') != $addSession->devType) {
             #  zero proggress $addSession->address = 0;
             #   $addSession->basicConfig = 0;
             #   $addSession->serviceConfig = "";
             #   $addSession->serviceMainConfig = "";
             #   $addSession->serviceConfig = "";
             #   $addSession->serviceRawConfig = "";               
            }
            $addSession->devType = $this->_getParam('devType');
            $this->_redirect("devices/addattributes");            
        }
        $this->view->devType = $addSession->devType;       
        #$devid = $this->_getParam('devType');
        # here edit of all attributes
    }
    
    public function addattributesAction() {
        
        $addSession = new Zend_Session_Namespace('addDevice');
        $this->view->headTitle($this->view->translate->_('Add new device'), 'PREPEND');        
        $devid = $this->_getParam('devid');
        $config = new Zend_Config_Ini(APPLICATION_PATH . "/forms/DefaultAttributesConfigForm.ini", 'development');
        $form = new Jhub1_Form($config->user->agent);
        $form = $this->selectFields($addSession->devType,$form,"/devices/addattributes");
   #     $this->view->form = $adoptedForm;
        if ($this->_request->isPost()) {
                $formData = $this->_request->getPost();
                if ($form->isValid($formData)) {
                    $addSession->devMainConfig = $formData;
                    $this->_redirect("devices/addsave");   
                } else {
                    $form->populate($formData);
                }
            }
        if(is_array($addSession->devMainConfig)){
            $form->populate($addSession->devMainConfig);
        }
        $this->view->form = $form;        

    }    
    
    public function addsaveAction() {
        $addSession = new Zend_Session_Namespace('addDevice');
        $em = $this->doctrineContainer->getEntityManager();

        $service = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $addSession->hubid));
     
        $attribs = new Jhub1db\Entity\Jhub1attributes($addSession->devMainConfig);
        $em->persist($attribs);    
      
        $device = new Jhub1db\Entity\Jhub1device($service[0]);
        $device->setAttributes($attribs);
        $device->setAddress($addSession->address);
        $device->setRemovable(1);
        $device->setVisible(1);
        $device->setDevicetype($addSession->devType);
        $em->persist($device);    
        $em->flush();
           
        # kill session with id after saving
        
        $this->_redirect("devices/index");
    }   
#END OF ADD DEVICE PROCESS

    public function actionsAction() {
        $this->_helper->layout()->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();

        $action = $this->_getParam('doaction');
        $deviceids = $this->_getParam('deviceid');
        
        $devicesItems = count($deviceids);
        if (preg_match("/^(static|dynamic|active|inactive|public|private|delete)/", $action) && $devicesItems > 0) {
            
            $em = $this->doctrineContainer->getEntityManager();
            
            if ($action == "static") {
                foreach($deviceids as $deviceid) {
                     $dev = $em->getRepository('Jhub1db\Entity\Jhub1device')->findBy(array('jhub1attributes' => $deviceid));
                     if(!$dev[0]->isFixedstatic()) {
                        $dev[0]->getAttributes()->setStatic(1);
                     }
                     $em->persist($dev[0]);    
                }
            } else if ($action == "dynamic") {
                foreach($deviceids as $deviceid) {
                     $dev = $em->getRepository('Jhub1db\Entity\Jhub1device')->findBy(array('jhub1attributes' => $deviceid));                     
                     if(!$dev[0]->isFixedstatic()) {
                        $dev[0]->getAttributes()->setStatic(0);
                     }
                     $em->persist($dev[0]);   
                }                
            } else if ($action == "active") {
                foreach($deviceids as $deviceid) {
                     $attr = $em->getRepository('Jhub1db\Entity\Jhub1attributes')->findBy(array('id' => $deviceid));
                     $attr[0]->setActive(1);
                     $em->persist($attr[0]);    
                }   
            } else if ($action == "inactive") {
                foreach($deviceids as $deviceid) {
                     $attr = $em->getRepository('Jhub1db\Entity\Jhub1attributes')->findBy(array('id' => $deviceid));
                     $attr[0]->setActive(0);
                     $em->persist($attr[0]);    
                }                   
            } else if ($action == "public") {
                foreach($deviceids as $deviceid) {
                     $dev = $em->getRepository('Jhub1db\Entity\Jhub1device')->findBy(array('jhub1attributes' => $deviceid));
                     $dev[0]->setAccesstype(1);
                     $em->persist($dev[0]);    
                }   
            } else if ($action == "private") {
                foreach($deviceids as $deviceid) {
                     $dev = $em->getRepository('Jhub1db\Entity\Jhub1device')->findBy(array('jhub1attributes' => $deviceid));
                     $dev[0]->setAccesstype(0);
                     $em->persist($dev[0]);    
                }                   
            }  else if ($action == "delete") {
                foreach($deviceids as $deviceid) {
                     $dev = $em->getRepository('Jhub1db\Entity\Jhub1device')->findBy(array('jhub1attributes' => $deviceid));
                     if($dev[0]->isRemovable()) {
                        $em->remove($dev[0]);  
                     }      
                }               
            } else {
                $this->_redirect("devices/index");                
            }
            $em->flush(); 
        } else {
           $this->_redirect("devices/index"); 
        }
        $this->_redirect("devices/index");
    }
        
    private function selectFields($deviceType, $form,$action = "") {
        $list = array(
            'name', 'orderi', 'precision',
            'step', 'unit', 'maxlimit', 'minlimit',
            'maxvalue', 'minvalue', 'threshold',
            'static', 'active','switchtype', 'truevalue',
            'falsevalue', 'pictogram'
         );
        $boolList = array (
            'name','orderi','truevalue',
            'falsevalue','pictogram','static', 'active','switchtype'
        );
        
        $realList = array (
            'name','orderi','pictogram','static', 'active','unit','maxlimit',
            'minlimit','maxvalue','minvalue','threshold','precision'
        );

        $intList = array (
            'name','orderi','pictogram','static', 'active','unit','maxlimit',
            'minlimit','maxvalue','minvalue','threshold','step'
        );

        $listList = array (
            'name','orderi','static', 'active','pictogram'
        );

        $colourList = array (
            'name','orderi','static', 'active','pictogram'
        );

        $textList = array (
            'name','orderi','pictogram'
        );
        
        foreach ($list as $key => $value) {
            if($deviceType == "bool") {
                $array2_key = array_search($value, $boolList);
            } else if ($deviceType == "colour") {
                $array2_key = array_search($value, $colourList);
            } else if ($deviceType == "list") {
                $array2_key = array_search($value, $listList);
            } else if ($deviceType == "text") {
                $array2_key = array_search($value, $textList);
            } else if ($deviceType == "int") {
                $array2_key = array_search($value, $intList);
            } else if ($deviceType == "real") {
                $array2_key = array_search($value, $realList);
            } else {
                $array2_key = array_search($value, $textList);
            }
            if ($array2_key === false)
                $result_array[] = $value;
        }

        foreach ($result_array as $element) {
             $form->removeElement($element);
        }
        if ($action != "") {
            $form->setAction($action);
        }
        return $form;
    }
}
